package com.supreme.nettyapp.generalserver.pingserver.service;

import com.supreme.nettyapp.generalserver.pingserver.handler.PingServerHandler;
import com.supreme.nettyapp.generalserver.pingserver.props.PingServerProps;
import com.supreme.nettyapp.generalserver.service.NettyServerService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttEncoder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class PingServerService implements NettyServerService {

    @Resource
    private PingServerProps pingServerProps;

    @Async(value = "nettyTask")
    @Override
    public void startNettyServer() {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup);
            serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline pipeline = socketChannel.pipeline();
                    pipeline.addLast("encoder", MqttEncoder.INSTANCE);
                    pipeline.addLast("decoder", new MqttDecoder());
                    pipeline.addLast(new PingServerHandler());
                }
            });

            ChannelFuture channelFuture = serverBootstrap.bind(pingServerProps.getPort()).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            System.out.println("e.getMessage() = " + e.getMessage());
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    @Override
    public void destroyNettyServer() {

    }
}
